#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
XBot集成启动脚本 - 合并版本
将管理后台和客户端功能完全集成到一个应用中
"""

import asyncio
import sys
import os
import threading
import time
import argparse
from typing import Dict, Any

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# 导入必要的模块
from common.logger import logger
from common.config_manager import config_manager
from main import XBotClient

class IntegratedXBot:
    """集成版XBot，将管理后台和客户端合并为一个应用"""
    
    def __init__(self, host='0.0.0.0', port=8888, debug=False):
        self.host = host
        self.port = port
        self.debug = debug
        self.client = None
        self.admin_thread = None
        self.client_thread = None
        self.running = False
        
    def start_admin_backend(self):
        """启动管理后台"""
        from admin_web.app import app as admin_app
        
        logger.info(f"🚀 启动管理后台 - 监听 {self.host}:{self.port}...")
        
        try:
            # 设置Flask配置
            admin_app.config['DEBUG'] = self.debug
            # 启动Flask应用
            admin_app.run(host=self.host, port=self.port, use_reloader=False, threaded=True)
        except Exception as e:
            logger.error(f"管理后台启动失败: {e}")
            import traceback
            traceback.print_exc()
    
    async def start_client(self):
        """启动XBot客户端"""
        logger.info("🤖 启动XBot客户端...")
        
        try:
            self.client = XBotClient()
            await self.client.run()
        except Exception as e:
            logger.error(f"XBot客户端启动失败: {e}")
            import traceback
            traceback.print_exc()
    
    def start(self):
        """启动集成应用"""
        self.running = True
        
        print("=" * 60)
        print("🎯 XBot集成版本启动 - 合并版")
        print("=" * 60)
        print(f"📱 管理后台地址: {self.host}:{self.port}")
        print("🔑 默认登录账号: admin / admin123")
        print("💡 请在管理后台中完成微信登录")
        print("🤖 XBot将自动检测登录状态并开始工作")
        print("=" * 60)
        
        # 在后台线程中启动管理后台
        self.admin_thread = threading.Thread(target=self.start_admin_backend, daemon=True)
        self.admin_thread.start()
        
        # 等待管理后台启动
        time.sleep(3)
        logger.info("✅ 管理后台启动完成")
        
        # 在主线程中启动客户端
        asyncio.run(self.start_client())
    
    def stop(self):
        """停止应用"""
        self.running = False
        if self.client:
            self.client.running = False
        logger.info("应用已停止")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='XBot集成版本启动脚本')
    parser.add_argument('--host', default='0.0.0.0', help='管理后台监听地址')
    parser.add_argument('--port', type=int, default=8888, help='管理后台监听端口')
    parser.add_argument('--debug', action='store_true', help='开启调试模式')
    
    args = parser.parse_args()
    
    try:
        app = IntegratedXBot(host=args.host, port=args.port, debug=args.debug)
        app.start()
    except KeyboardInterrupt:
        print("\n🛑 收到停止信号，正在退出...")
    except Exception as e:
        print(f"\n❌ 程序运行异常: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main() 